<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目" prop="projectId">
        <el-select v-model="queryParams.projectId" placeholder="请选择项目" clearable @change="handleQuery">
          <el-option
            v-for="project in projectOptions"
            :key="project.projectId"
            :label="project.projectName"
            :value="project.projectId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="文档类型" prop="docType">
        <el-select v-model="queryParams.docType" placeholder="请选择文档类型" clearable @change="handleQuery">
          <el-option label="文件" value="file" />
          <el-option label="文件夹" value="folder" />
        </el-select>
      </el-form-item>
      <el-form-item label="文档名称" prop="docName">
        <el-input
          v-model="queryParams.docName"
          placeholder="请输入文档名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-dropdown @command="handleNewCommand" v-hasPermi="['pm:document:add']">
          <el-button type="primary" plain icon="Plus">
            新建<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="file" icon="Upload">新建文件</el-dropdown-item>
              <el-dropdown-item command="folder" icon="FolderAdd">新建文件夹</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 文档树表格 -->
    <el-table
      v-loading="loading"
      :data="documentList"
      row-key="docId"
      :tree-props="{ children: 'childrenVo', hasChildren: 'hasChildren' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="文档名称" prop="docName" min-width="200" />
      <el-table-column label="类型" prop="docType" width="100" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.docType === 'folder'" type="primary">
            <el-icon><Folder /></el-icon>
            文件夹
          </el-tag>
          <el-tag v-else type="success">
            <el-icon><Document /></el-icon>
            {{ scope.row.fileExtension || '文件' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="fileSizeFormatted" label="大小" width="100" align="center" />
      <el-table-column prop="downloadCount" label="下载次数" width="100" align="center" />
      <el-table-column prop="uploaderName" label="上传者" width="120" />
      <el-table-column prop="uploadTimeFormatted" label="上传时间" width="160" />
      <el-table-column prop="isPublic" label="公开" width="80" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.isPublic ? 'success' : 'info'">
            {{ scope.row.isPublic ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="View"
            @click="handleView(scope.row)"
            v-hasPermi="['pm:document:query']"
          >查看</el-button>
          <el-button
            link
            type="success"
            icon="Upload"
            @click="handleUploadToFolder(scope.row)"
            v-hasPermi="['pm:document:add']"
            v-if="scope.row.docType === 'folder'"
          >上传文件</el-button>
          <el-button
            link
            type="primary"
            icon="Download"
            @click="handleDownload(scope.row)"
            v-hasPermi="['pm:document:download']"
            v-if="scope.row.docType === 'file'"
          >下载</el-button>
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pm:document:edit']"
          >修改</el-button>
          <el-button
            link
            type="danger"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pm:document:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 修改文件夹对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body v-if="form.docType === 'folder'">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目" prop="projectId">
          <el-select v-model="form.projectId" placeholder="请选择项目" disabled>
            <el-option
              v-for="project in projectOptions"
              :key="project.projectId"
              :label="project.projectName"
              :value="project.projectId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="任务" prop="taskId">
          <el-select v-model="form.taskId" placeholder="请选择任务" clearable disabled>
            <el-option
              v-for="task in taskOptions"
              :key="task.taskId"
              :label="task.taskName"
              :value="task.taskId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="父文件夹" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="folderTreeOptions"
            :props="{ label: 'docName', value: 'docId', children: 'childrenVo' }"
            placeholder="请选择父文件夹（不选择则为根目录）"
            clearable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item label="文件夹名称" prop="docName">
          <el-input v-model="form.docName" placeholder="请输入文件夹名称" />
        </el-form-item>
        <el-form-item label="是否公开" prop="isPublic">
          <el-radio-group v-model="form.isPublic">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看/修改文件对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body v-if="form.docType === 'file'">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目" prop="projectId">
          <el-select v-model="form.projectId" placeholder="请选择项目" :disabled="title === '查看文档'">
            <el-option
              v-for="project in projectOptions"
              :key="project.projectId"
              :label="project.projectName"
              :value="project.projectId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="任务" prop="taskId">
          <el-select v-model="form.taskId" placeholder="请选择任务" clearable :disabled="title === '查看文档'">
            <el-option
              v-for="task in taskOptions"
              :key="task.taskId"
              :label="task.taskName"
              :value="task.taskId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文件名称" prop="docName">
          <el-input v-model="form.docName" placeholder="请输入文件名称" :disabled="title === '查看文档'" />
        </el-form-item>
        <el-form-item label="所在文件夹" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="folderTreeOptions"
            :props="{ label: 'docName', value: 'docId', children: 'childrenVo' }"
            placeholder="请选择文件夹（不选择则为根目录）"
            clearable
            check-strictly
            :render-after-expand="false"
            :disabled="title === '查看文档'"
          />
        </el-form-item>
        <el-form-item label="当前文件" v-if="form.filePath">
          <div class="current-file">
            <el-icon class="file-icon"><Document /></el-icon>
            <span class="file-name">{{ form.docName }}</span>
            <el-tag size="small" type="info">{{ form.fileExtension }}</el-tag>
            <el-button size="small" type="primary" @click="handleDownload(form)">下载</el-button>
          </div>
        </el-form-item>
        <el-form-item label="替换文件" v-if="title === '修改文档'">
          <el-upload
            ref="updateUploadRef"
            :limit="1"
            :on-exceed="handleExceed"
            :before-upload="beforeUpload"
            :auto-upload="false"
            :on-change="handleUpdateFileChange"
            drag
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将新文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持图片、Office文档、PDF、压缩包等文件，且不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="是否公开" prop="isPublic">
          <el-radio-group v-model="form.isPublic" :disabled="title === '查看文档'">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :disabled="title === '查看文档'" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="title === '修改文档'" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 上传文件对话框 -->
    <el-dialog title="上传文件" v-model="uploadOpen" width="500px" append-to-body>
      <el-form ref="uploadFormRef" :model="uploadForm" :rules="uploadRules" label-width="80px">
        <el-form-item label="项目" prop="projectId">
          <el-select v-model="uploadForm.projectId" placeholder="请选择项目" @change="onProjectChange">
            <el-option
              v-for="project in projectOptions"
              :key="project.projectId"
              :label="project.projectName"
              :value="project.projectId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="任务" prop="taskId">
          <el-select v-model="uploadForm.taskId" placeholder="请选择任务" clearable>
            <el-option
              v-for="task in taskOptions"
              :key="task.taskId"
              :label="task.taskName"
              :value="task.taskId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上传到文件夹" prop="parentId">
          <el-tree-select
            v-model="uploadForm.parentId"
            :data="folderTreeOptions"
            :props="{ label: 'docName', value: 'docId', children: 'childrenVo' }"
            placeholder="请选择文件夹"
            clearable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item label="文件" prop="file">
          <el-upload
            ref="uploadRef"
            :limit="1"
            :on-exceed="handleExceed"
            :before-upload="beforeUpload"
            :auto-upload="false"
            :on-change="handleFileChange"
            drag
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持图片、Office文档、PDF、压缩包等文件，且不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="文档名称" prop="docName">
          <el-input v-model="uploadForm.docName" placeholder="留空则使用原文件名" />
        </el-form-item>
        <el-form-item label="是否公开" prop="isPublic">
          <el-radio-group v-model="uploadForm.isPublic">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitUpload">确 定</el-button>
          <el-button @click="cancelUpload">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新建文件夹对话框 -->
    <el-dialog title="新建文件夹" v-model="folderOpen" width="500px" append-to-body>
      <el-form ref="folderFormRef" :model="folderForm" :rules="folderRules" label-width="80px">
        <el-form-item label="项目" prop="projectId">
          <el-select v-model="folderForm.projectId" placeholder="请选择项目" @change="onFolderProjectChange">
            <el-option
              v-for="project in projectOptions"
              :key="project.projectId"
              :label="project.projectName"
              :value="project.projectId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="任务" prop="taskId">
          <el-select v-model="folderForm.taskId" placeholder="请选择任务" clearable>
            <el-option
              v-for="task in taskOptions"
              :key="task.taskId"
              :label="task.taskName"
              :value="task.taskId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="父文件夹" prop="parentId">
          <el-tree-select
            v-model="folderForm.parentId"
            :data="folderTreeOptions"
            :props="{ label: 'docName', value: 'docId', children: 'childrenVo' }"
            placeholder="选择父文件夹（可选）"
            clearable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item label="文件夹名称" prop="folderName">
          <el-input v-model="folderForm.folderName" placeholder="请输入文件夹名称" />
        </el-form-item>
        <el-form-item label="是否公开" prop="isPublic">
          <el-radio-group v-model="folderForm.isPublic">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFolder">确 定</el-button>
          <el-button @click="cancelFolder">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Document" lang="ts">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox, ElUpload } from 'element-plus'
import { Folder, Document, UploadFilled, ArrowDown, Plus, Upload, FolderAdd } from '@element-plus/icons-vue'
import { listDocument, getDocument, addDocument, updateDocument, delDocument, uploadFile, createFolder, downloadFile } from '@/api/pm/document'
import { listProject } from '@/api/pm/project'
import { listTask } from '@/api/pm/task'
import type { PmProjectDocumentVO, PmProjectDocumentQuery } from '@/api/pm/document'

const { proxy } = getCurrentInstance() as any

// 响应式数据
const documentList = ref<PmProjectDocumentVO[]>([])
const loading = ref(true)
const showSearch = ref(true)
const ids = ref<number[]>([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const open = ref(false)
const uploadOpen = ref(false)
const folderOpen = ref(false)

// 项目选项
const projectOptions = ref<any[]>([])
const taskOptions = ref<any[]>([])

// 查询参数
const queryParams = reactive<PmProjectDocumentQuery>({
  pageNum: 1,
  pageSize: 10,
  projectId: undefined,
  taskId: undefined,
  parentId: undefined,
  docType: undefined,
  docName: undefined,
  isPublic: undefined
})

// 表单数据
const form = ref<PmProjectDocumentVO>({})
const uploadForm = ref({
  projectId: undefined,
  taskId: undefined,
  parentId: undefined,
  file: null as File | null,
  docName: '',
  isPublic: false
})
const folderForm = ref({
  projectId: undefined,
  taskId: undefined,
  parentId: undefined,
  folderName: '',
  isPublic: false
})

// 文件夹树形选项
const folderTreeOptions = ref<any[]>([])

// 表单验证规则
const rules = {
  projectId: [{ required: true, message: '项目不能为空', trigger: 'change' }],
  docName: [{ required: true, message: '文档名称不能为空', trigger: 'blur' }],
  docType: [{ required: true, message: '文档类型不能为空', trigger: 'change' }]
}

const uploadRules = {
  projectId: [{ required: true, message: '项目不能为空', trigger: 'change' }],
  parentId: [{ required: true, message: '请选择文件夹', trigger: 'change' }],
  file: [{ required: true, message: '请选择文件', trigger: 'change' }]
}

const folderRules = {
  projectId: [{ required: true, message: '项目不能为空', trigger: 'change' }],
  folderName: [{ required: true, message: '文件夹名称不能为空', trigger: 'blur' }]
}

// 表单引用
const queryFormRef = ref()
const formRef = ref()
const uploadFormRef = ref()
const folderFormRef = ref()
const uploadRef = ref<InstanceType<typeof ElUpload>>()

// 加载项目列表
const loadProjects = () => {
  listProject({ pageNum: 1, pageSize: 1000 }).then(res => {
    projectOptions.value = res.rows || []
  })
}

// 加载任务列表
const loadTasksByProject = (projectId?: number) => {
  if (!projectId) {
    taskOptions.value = []
    return
  }
  listTask({ projectId, pageNum: 1, pageSize: 1000 }).then(res => {
    taskOptions.value = res.rows || []
  })
}

// 上传文件时项目变更
const onProjectChange = (projectId: number) => {
  loadTasksByProject(projectId)
  loadFolderTree(projectId)
}

// 新建文件夹时项目变更
const onFolderProjectChange = (projectId: number) => {
  loadTasksByProject(projectId)
  loadFolderTree(projectId)
}

// 加载文件夹树
const loadFolderTree = (projectId: number, excludeDocId?: number) => {
  if (!projectId) {
    folderTreeOptions.value = []
    return
  }
  // 从当前文档列表中筛选出文件夹
  const folders = getAllFolders(documentList.value)
  // 排除当前编辑的文档，避免循环引用
  const filteredFolders = excludeDocId ? 
    folders.filter(folder => folder.docId !== excludeDocId) : 
    folders
  folderTreeOptions.value = buildFolderTree(filteredFolders)
}

// 获取所有文件夹
const getAllFolders = (documents: PmProjectDocumentVO[]): PmProjectDocumentVO[] => {
  const folders: PmProjectDocumentVO[] = []
  
  const traverse = (docs: PmProjectDocumentVO[]) => {
    docs.forEach(doc => {
      if (doc.docType === 'folder') {
        folders.push(doc)
      }
      if (doc.childrenVo && doc.childrenVo.length > 0) {
        traverse(doc.childrenVo)
      }
    })
  }
  
  traverse(documents)
  return folders
}

// 构建文件夹树
const buildFolderTree = (folders: PmProjectDocumentVO[]) => {
  const map = new Map()
  const roots: PmProjectDocumentVO[] = []
  
  // 创建映射，使用深拷贝避免修改原始数据
  folders.forEach(folder => {
    const folderCopy = JSON.parse(JSON.stringify(folder))
    folderCopy.childrenVo = []
    map.set(folder.docId, folderCopy)
  })
  
  // 构建树形结构
  folders.forEach(folder => {
    const folderCopy = map.get(folder.docId)
    if (folder.parentId && map.has(folder.parentId)) {
      map.get(folder.parentId).childrenVo.push(folderCopy)
    } else {
      roots.push(folderCopy)
    }
  })
  
  return roots
}

// 查询文档列表
const getList = () => {
  loading.value = true
  listDocument(queryParams).then(response => {
    // 后端已经构建了树形结构，直接使用
    documentList.value = response.rows || []
    total.value = response.total || 0
    
    // 加载文件夹树（用于选择父文件夹）
    if (queryParams.projectId) {
      loadFolderTree(queryParams.projectId)
    }
    
    loading.value = false
  })
}

// 构建文档树形结构
const buildDocumentTree = (documents: PmProjectDocumentVO[]) => {
  const map = new Map<number, PmProjectDocumentVO>()
  const roots: PmProjectDocumentVO[] = []
  
  // 创建映射，初始化children数组
  documents.forEach(doc => {
    doc.childrenVo = []
    map.set(doc.docId!, doc)
  })
  
  // 构建树形结构
  documents.forEach(doc => {
    if (doc.parentId && map.has(doc.parentId)) {
      // 有父节点，添加到父节点的children中
      map.get(doc.parentId)!.childrenVo!.push(doc)
    } else {
      // 没有父节点，作为根节点
      roots.push(doc)
    }
  })
  
  // 为文件夹设置hasChildren属性
  const setHasChildren = (docs: PmProjectDocumentVO[]) => {
    docs.forEach(doc => {
      if (doc.docType === 'folder') {
        doc.hasChildren = doc.childrenVo && doc.childrenVo.length > 0
        if (doc.childrenVo && doc.childrenVo.length > 0) {
          setHasChildren(doc.childrenVo)
        }
      } else {
        // 文件不能有子项
        doc.hasChildren = false
        doc.childrenVo = []
      }
    })
  }
  
  setHasChildren(roots)
  return roots
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection: PmProjectDocumentVO[]) => {
  ids.value = selection.map(item => item.docId!)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 新建下拉菜单操作
const handleNewCommand = (command: string) => {
  if (command === 'file') {
    handleUpload()
  } else if (command === 'folder') {
    handleCreateFolder()
  }
}

// 上传文件按钮操作
const handleUpload = () => {
  resetUpload()
  uploadOpen.value = true
}

// 上传文件到指定文件夹
const handleUploadToFolder = (folder: PmProjectDocumentVO) => {
  resetUpload()
  uploadForm.value.projectId = folder.projectId
  uploadForm.value.parentId = folder.docId
  uploadOpen.value = true
}

// 新建文件夹按钮操作
const handleCreateFolder = () => {
  resetFolder()
  folderOpen.value = true
}

// 查看按钮操作
const handleView = (row: PmProjectDocumentVO) => {
  reset()
  const docId = row.docId || 0
  getDocument(docId).then(response => {
    // 使用深拷贝避免修改原始数据
    form.value = JSON.parse(JSON.stringify(response.data))
    open.value = true
    title.value = '查看文档'
  })
}

// 修改按钮操作
const handleUpdate = (row: PmProjectDocumentVO) => {
  reset()
  const docId = row.docId || 0
  getDocument(docId).then(response => {
    // 使用深拷贝避免修改原始数据
    form.value = JSON.parse(JSON.stringify(response.data))
    // 加载文件夹树选项（用于修改时选择父文件夹）
    if (form.value.projectId) {
      loadFolderTree(form.value.projectId, form.value.docId)
    }
    open.value = true
    title.value = '修改文档'
  })
}

// 下载按钮操作
const handleDownload = (row: PmProjectDocumentVO) => {
  const docId = row.docId || 0
  
  downloadFile(docId).then(response => {
    const blob = new Blob([response])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = row.docName || 'download'
    link.click()
    window.URL.revokeObjectURL(url)
    ElMessage.success('文件下载成功')
  }).catch(error => {
    ElMessage.error('文件下载失败: ' + (error.message || '未知错误'))
  })
}

// 删除按钮操作
const handleDelete = (row: PmProjectDocumentVO) => {
  const docIds = row.docId || 0
  ElMessageBox.confirm('是否确认删除文档编号为"' + docIds + '"的数据项？').then(() => {
    return delDocument([docIds])
  }).then(() => {
    getList()
    ElMessage.success('删除成功')
  })
}

// 文件上传相关
const handleExceed = () => {
  ElMessage.warning('只能上传一个文件')
}

const beforeUpload = (file: File) => {
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('上传文件大小不能超过 10MB!')
  }
  return isLt10M
}

const handleFileChange = (file: any) => {
  uploadForm.value.file = file.raw
}

// 修改文件时的文件变更处理
const handleUpdateFileChange = (file: any) => {
  form.value.newFile = file.raw
}

// 提交按钮
const submitForm = () => {
  formRef.value?.validate((valid: boolean) => {
    if (!valid) return
    if (form.value.docId != null) {
      // 修改文档
      if (form.value.docType === 'file' && form.value.newFile) {
        // 文件修改且上传了新文件
        const formData = new FormData()
        formData.append('file', form.value.newFile)
        formData.append('projectId', form.value.projectId)
        formData.append('taskId', form.value.taskId || '')
        formData.append('parentId', form.value.parentId || '')
        formData.append('docName', form.value.docName)
        formData.append('isPublic', form.value.isPublic)
        
        uploadFile(formData).then(response => {
          ElMessage.success('文件替换成功')
          open.value = false
          getList()
        })
      } else {
        // 普通修改（文件夹或文件信息修改）
        updateDocument(form.value).then(response => {
          ElMessage.success('修改成功')
          open.value = false
          getList()
        })
      }
    } else {
      addDocument(form.value).then(response => {
        ElMessage.success('新增成功')
        open.value = false
        getList()
      })
    }
  })
}

// 提交上传
const submitUpload = () => {
  uploadFormRef.value?.validate((valid: boolean) => {
    if (!valid) return
    if (!uploadForm.value.file) {
      ElMessage.error('请选择文件')
      return
    }
    uploadFile(
      uploadForm.value.file,
      uploadForm.value.projectId!,
      uploadForm.value.taskId,
      uploadForm.value.parentId,
      uploadForm.value.docName || undefined,
      uploadForm.value.isPublic
    ).then(response => {
      ElMessage.success('上传成功')
      uploadOpen.value = false
      getList()
    })
  })
}

// 提交文件夹
const submitFolder = () => {
  folderFormRef.value?.validate((valid: boolean) => {
    if (!valid) return
    createFolder(
      folderForm.value.projectId!,
      folderForm.value.taskId,
      folderForm.value.parentId,
      folderForm.value.folderName,
      folderForm.value.isPublic
    ).then(response => {
      ElMessage.success('创建成功')
      folderOpen.value = false
      getList()
    })
  })
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

const cancelUpload = () => {
  uploadOpen.value = false
  resetUpload()
}

const cancelFolder = () => {
  folderOpen.value = false
  resetFolder()
}

// 表单重置
const reset = () => {
  form.value = {}
  formRef.value?.resetFields()
}

const resetUpload = () => {
  uploadForm.value = {
    projectId: undefined,
    taskId: undefined,
    parentId: undefined,
    file: null,
    docName: '',
    isPublic: false
  }
  uploadFormRef.value?.resetFields()
  uploadRef.value?.clearFiles()
}

// 获取文件夹名称
const getFolderName = (folderId: number) => {
  const folder = documentList.value.find(item => item.docId === folderId)
  return folder ? folder.docName : '未知文件夹'
}

// 获取文件夹路径
const getFolderPath = (folderId: number) => {
  const path: string[] = []
  
  const findPath = (docs: PmProjectDocumentVO[], targetId: number): boolean => {
    for (const doc of docs) {
      if (doc.docId === targetId) {
        path.unshift(doc.docName)
        return true
      }
      if (doc.childrenVo && doc.childrenVo.length > 0) {
        if (findPath(doc.childrenVo, targetId)) {
          path.unshift(doc.docName)
          return true
        }
      }
    }
    return false
  }
  
  findPath(documentList.value, folderId)
  return path.join(' / ')
}


const resetFolder = () => {
  folderForm.value = {
    projectId: undefined,
    taskId: undefined,
    parentId: undefined,
    folderName: '',
    isPublic: false
  }
  folderFormRef.value?.resetFields()
}

// 页面加载时
onMounted(() => {
  loadProjects()
  getList()
})
</script>

<style scoped>


.current-file {
  display: flex;
  align-items: center;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.current-file .file-name {
  margin: 0 8px;
  flex: 1;
}

.current-file .el-tag {
  margin-right: 8px;
}
</style>
